<template>
  <div class="login_max_box" v-loading="loading" element-loading-text="正在登录中">
    <div class="form_box">
      <h3>欢迎登录界面</h3>
<el-form label-width="100px" :model="ruleForm" class="demo-ruleForm" status-icon :rules="rules" style="position:relative">
  <el-form-item label="用户名" prop="username">
    <el-input type="text" v-model="ruleForm.name" placeholder="请输入用户名"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="password">
    <el-input type="password" v-model="ruleForm.passwd" placeholder="请输入密码" show-password></el-input>
  </el-form-item>
  <el-form-item label="验证码" prop="checkcode">
    <el-input type="text" class="check_code" v-model="ruleForm.checkcode" style="width:40%" placeholder="验证码"></el-input>
  </el-form-item>
  <valid-code  :value.sync="validCodes" class="checkcode" style="position:absolute"></valid-code>
</el-form>
    <el-row>
  <el-button  type="primary"  @click="login()" class="btn">登录</el-button>
  <!-- <el-button  @click="submitForm('ruleForm')">提交</el-button> -->
</el-row>
      <el-row>
        <el-col :span="6"><el-link @click="oauth2Login">第三方登陆</el-link></el-col>
        <el-col :span="4"><el-link @click="register">注册</el-link></el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import { Login } from "@/request/api"
import {Message} from "_element-ui@2.15.6@element-ui";
import {getUserByToken} from "../request/api";
// import { Message } from 'element-ui';
// import axios from 'axios'
export default {
  name:"Login",

  data(){
    // eslint-disable-next-line no-unused-vars
     var checkAge = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('验证码不能为空'));
        }
          if (value != this.validCodes) {
            console.log(value)
            // console.log(this.validCodes)
            callback(new Error('验证码不正确'));
          } else {
              callback();
            }
          
      };
    // eslint-disable-next-line no-unused-vars
      var validatePass = (rule, value, callback) => {
        // 帐号是否合法(字母开头，允许5-16字节，允许字母数字下划线)：^[a-zA-Z][a-zA-Z0-9_]{4,15}$
         var reg = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
        if (value === '') {
          callback(new Error('请输入用户名'));
        } else if(!reg.test(value)){
          callback(new Error('请输入字母开头的合法用户名'));
          }
          callback();
        
      };
    // eslint-disable-next-line no-unused-vars
      var validatePass2 = (rule, value, callback) => {
        // n位的数字：^\d{n}$
        var reg = /^\d{6}$/;
        if (value === '') {
          callback(new Error('请输入密码'));
        } else if (value !==this.ruleForm.password || !reg.test(value)) {
          callback(new Error('密码不正确!'));
        } else {
          callback();
        }
      };
      
		return{
      loading:false,
      validCodes:'',
      redirect_uri: '/',
      ruleForm:{
          name: '',
          passwd: '',
          checkcode: '',
        },
          rules: {
          // username: [
          //   { validator: validatePass, trigger: 'blur' }
          // ],
          // password: [
          //   { validator: validatePass2, trigger: 'blur' }
          // ],
          // checkcode: [
          //   { validator: checkAge, trigger: 'blur' }
          // ]
        }
		}

  },
 created() {
   const query = this.$route.query;
   if(query.redirect_uri) {
     this.redirect_uri = query.redirect_uri
   }
 },
  methods:{
    register() {
      this.$router.push({
        path: "/register",
        query: {
          redirect_uri: '/login?redirect_uri=' + this.redirect_uri
        }
      })
    },
    oauth2Login() {
      window.location.href='/oauth2/login' +
          '?redirect_uri=/oauth2/callback?redirect_uri=' + this.redirect_uri +'&client_id=1000000001&state=1&response_type=code';
    },

login(){
   this.loading=true;
			Login(this.ruleForm).then(res=>{
        this.loading=false;
        if(res.code !== 0) {
          Message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
          return
        }
        getUserByToken({access_token: res.data.access_token}).then(res1=> {
          if (res1.code !== 0) {
            Message({
              showClose: true,
              message: res1.msg,
              type: 'error'
            });
            return
          }
          if (!res1.data) {
            Message({
              showClose: true,
              message: '用户获取失败',
              type: 'error'
            });
            return
          }
          localStorage.setItem('token', JSON.stringify(res.data))
          localStorage.setItem('user', res1.data.name)
          this.loading=false;
          this.$message({
            showClose: true,
            message: '登录成功',
            type: 'success'
          });
          this.$router.replace(this.redirect_uri)
        })
    })
     .catch(error => {

       console.log(error)
       this.loading=false;
           this.$message({
          showClose: true,
          message: '登录失败',
          type: 'error'
        });
        return error
        });
},
  

  },
  mounted(){
  //   axios.post('http://www.vicor.com/index.php/admin/login', {
  //  username: 'admin',
  //       password: '123456'
  // })
  // .then(function (response) {
  //   console.log(response);
  // })
  // .catch(function (error) {
  //   console.log(error);
  // })
  }
}
</script>
<style scoped>
.login_max_box{
  width: 100%;
  height: 100%;
  background: url(../assets/login-bg.jpg);
  background-size: 100%;
  position: fixed;  
}
.form_box{
  width: 400px;
  height: 400px;
  margin-top: 10%;
  margin-left: 60%;
  background: #fff;
}
h3{
   text-align: center;
   letter-spacing: 4px;
   font-size: 18px;
   padding-top: 65px;
   padding-bottom: 40px;
}
.checkcode{
  width: 80px;
  height:40px;
  position: absolute;
    right: 60px;
    bottom: 0;
}
.btn{
  width: 100%;
}
.el-input{
  width: 80%;
}
.btn[data-v-26084dc2]{
    width: 56%;
    margin-left: 88px;
}

</style>